package com.suncaper.shop.service;


import com.suncaper.shop.component.Utils;
import com.suncaper.shop.domain.User;
import com.suncaper.shop.domain.UserExample;
import com.suncaper.shop.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.HttpRetryException;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UserMapper usermapper;

    private UserExample userExample;

    @Autowired
    private EmailService emailService;

    public List<User> ListUser() {

        return usermapper.findAll();
    }


    public User getUserById(Integer uid) {
        return usermapper.selectByPrimaryKey(uid);
    }

    public void save(User user) {


        usermapper.insert(user);
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     */
    public Boolean login(String username, String password, HttpServletRequest requset) {
        userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username)
                .andPasswordEqualTo(password);
        List<User> userList = null;
        try {
            userList = usermapper.selectByExample(userExample);
            if (userList.size() == 0) {

                return false;

            } else {
                requset.getSession().setAttribute("userInfo", userList.get(0));
//                session.setAttribute("userInfo",userList.get(0));
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }


    /**
     * 用户退出
     *
     * @param session
     * @param map
     */
    public void logout(HttpSession session, Map<String, Object> map) {
        if (session.getAttribute("userInfo") != null) {
            session.invalidate();
            map.put("msg", "退出成功");
        }

    }


    /**
     * 记住用户
     *
     * @param remember
     */
    public void rememberme(String remember, String savename, String savapassword, HttpServletResponse response) {
        if (remember.equals("forever")) {
            Cookie name = new Cookie("savename", savename);
            name.setMaxAge(100);
            response.addCookie(name);
        }
    }

    public void getCookie(HttpServletRequest request, Map<String, Object> map) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("savename")) {
                map.put(cookie.getName(), cookie.getValue());
            }

        }
    }

    /**
     * 简易商家注册
     *
     * @param check
     * @param id
     * @param session
     */
    public void register(String check, Integer id, HttpSession session) {
        if (check.equals("1234")) {
            System.out.println("Register");
            User user = usermapper.selectByPrimaryKey(id);
            user.setAccess(1);
            usermapper.updateByPrimaryKey(user);
            session.setAttribute("userInfo", user);
        }
    }

    public boolean updateById(User user, Map<String, Object> map, String password, String password1, String password2, HttpSession session) {

        User user1 = usermapper.selectByPrimaryKey(user.getId());
        if (user1.getPassword().equals(password)) {
            if (password1.equals(password2)) {
                user.setPassword(password1);
                usermapper.updateByPrimaryKey(user);
                session.setAttribute("userInfo", user);
                return true;
            }
            map.put("msg", "两次输入的密码不同");
            return false;
        }

        map.put("msg", "输入原密码错误");
        return false;
    }

    public boolean checkcode(String email, String code, String Ocode, Map map) {
        if (code.equals(Ocode)) {
            userExample = new UserExample();
            userExample.createCriteria().andUsernameEqualTo(email);
            List<User> list = usermapper.selectByExample(userExample);


            if(list.size()==0){
                //不是用户名
                userExample=new UserExample();
                userExample.createCriteria().andEmailEqualTo(email);
                List<User> list1 = usermapper.selectByExample(userExample);
                if(list1.size()==0){
                    map.put("msg","邮箱或用户名输入错误");
                    return false;
                }else {
                    User user1 = list1.get(0);
                    user1.setPassword("");
                    usermapper.updateByPrimaryKey(user1);
                    return true;
                }
            }
            User user= list.get(0);
            user.setPassword("");
            usermapper.updateByPrimaryKey(user);
            return true;
        }
        map.put("msg", "输入CODE错误");
        return false;
    }

    public String salerLogin(HttpServletRequest request, String username, String password, Map map, HttpServletResponse response) {

        String re = null;
//        如果选择 Remember me 就记录Cookie的值
        if (request.getParameter("rememberme") != null) {
            re = request.getParameter("rememberme");
        }
        Boolean s_f = login(username, password, request);
        if (s_f) {
            map.put("isLogin", true);
            if (re != null) {
                rememberme(re, username, password, response);
            }
            userExample = new UserExample();
            userExample.createCriteria().andUsernameEqualTo(username);
            List<User> users = usermapper.selectByExample(userExample);
            if (users.size() > 0) {
                if (users.get(0).getAccess() != 1) {
                    map.put("msg", "没有权限");
                    return "saler_login";
                }
            }
            return "redirect:/account_saler";
        } else {
            map.put("msg", "用户名密码错误");
            return "saler_login";
        }
    }

    public String restPassword(String email,String code,HttpSession session, Map map){
        if (email != null && session.getAttribute("code") == null) {
            userExample=new UserExample();
            userExample.createCriteria().andUsernameEqualTo(email);
            List<User> users = usermapper.selectByExample(userExample);
            if(users.size()==0){
                //不是用户名
                userExample=new UserExample();
                userExample.createCriteria().andEmailEqualTo(email);
                List<User> users1 = usermapper.selectByExample(userExample);
                if(users1.size()==0){
                    map.put("msg","邮箱或用户名输入错误");
                    return "lost_password";
                }
            }else{
                User user = users.get(0);
                email=user.getEmail();
            }

            Utils utils = new Utils();
            String s = utils.getCode().substring(0, 4);
            String msg = "你的验证码是" + s;
            emailService.sendMail("重置密码", msg, email);
            session.setAttribute("code", s);
        }
        if (code != null) {
            if(checkcode(email, code, (String) session.getAttribute("code"), map)){
                return "index";
            }
        }
        return "lost_password";
    }

}
